package com.ynkbny.tasks;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ynkbny.aspect.TaskOperationLog;
import com.ynkbny.lgapi.User;
import com.ynkbny.lgapi.YnBk;
import com.ynkbny.service.BaseJob;
import com.ynkbny.service.TEpDataCollectConfigureService;
import com.ynkbny.service.TokenService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @Author YY
 * @Date 2023/8/29 9:28
 */
@Component
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class UpdateDataCollectConfigure implements BaseJob {

    private static final Logger log = LoggerFactory.getLogger(UpdateToken.class);

    @Resource
    private User user;

    @Resource
    private TokenService tokenService;

    @Resource
    private TEpDataCollectConfigureService dataCollectConfigureService;

    /**
     * 同步老狗平台的采集配置项
     * @Author YY
     */
    @Override
    @TaskOperationLog(description = "同步老狗平台的采集配置项")
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        // 获取老狗 第三方通用API接口 token
        String token = tokenService.getLaoGouToken();

        // 查询项目列表
        JSONArray jsonArray = queryProjectList(token);
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                // 从老狗平台拉取采集配置项并更新或插入数据
                dataCollectConfigureService.saveOrUpdateBatchData(jsonArray.getJSONObject(i).getInteger("id"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询项目列表
     * @Author YY
     * @param token 老狗 第三方通用API接口 token
     * @return JSONArray
     */
    private JSONArray queryProjectList(String token){
        HashMap<String, Object> map = new HashMap<>(1);
        map.put("isAll",true);
        JSONObject queryProjectResult = user.queryProjectList(token,map);
        return queryProjectResult.getJSONArray("data");
    }
}
